import 'package:flutter/material.dart';
import 'package:flutter/gestures.dart';
import 'package:jiyun_behavior/screens/basic_chart_screen.dart';
import 'package:jiyun_behavior/utils/app_theme.dart';
import 'package:jiyun_behavior/widgets/custom_button.dart';

class UserInfoScreen extends StatefulWidget {
  const UserInfoScreen({Key? key}) : super(key: key);

  @override
  State<UserInfoScreen> createState() => _UserInfoScreenState();
}

class _UserInfoScreenState extends State<UserInfoScreen> {
  final _formKey = GlobalKey<FormState>();
  final _nameController = TextEditingController();
  String _gender = '男';
  String _selectedYear = '1983年';
  String _selectedMonth = '三月';
  String _selectedDay = '初四';
  String _selectedTime = '辰时 (07:00-09:00)';
  String _selectedProvince = '北京市';
  String _selectedCity = '北京市';
  String _selectedOccupation = '企业职员';
  String _selectedMaritalStatus = '已婚';
  bool _isAgreed = true;

  // 生成年份选项
  List<String> _generateYears() {
    List<String> years = [];
    for (int i = 1950; i <= 2010; i++) {
      years.add('$i年');
    }
    return years;
  }

  // 生成农历月份选项
  List<String> _generateMonths() {
    return [
      '正月', '二月', '三月', '四月', '五月', '六月',
      '七月', '八月', '九月', '十月', '冬月', '腊月'
    ];
  }

  // 生成农历日期选项
  List<String> _generateDays() {
    List<String> days = [];
    for (int i = 1; i <= 30; i++) {
      if (i <= 10) {
        days.add('初$i');
      } else if (i <= 20) {
        days.add('十${i - 10}');
      } else if (i < 30) {
        days.add('廿${i - 20}');
      } else {
        days.add('三十');
      }
    }
    return days;
  }

  // 生成时辰选项
  List<String> _generateTimeSlots() {
    return [
      '子时 (23:00-01:00)', '丑时 (01:00-03:00)', '寅时 (03:00-05:00)',
      '卯时 (05:00-07:00)', '辰时 (07:00-09:00)', '巳时 (09:00-11:00)',
      '午时 (11:00-13:00)', '未时 (13:00-15:00)', '申时 (15:00-17:00)',
      '酉时 (17:00-19:00)', '戌时 (19:00-21:00)', '亥时 (21:00-23:00)'
    ];
  }

  void _generateChart() {
    if (_formKey.currentState!.validate() && _isAgreed) {
      // 这里添加生成命理基本盘的逻辑
      // 跳转到基本盘展示页面
      Navigator.push(
        context,
        MaterialPageRoute(builder: (context) => const BasicChartScreen()),
      );
    } else if (!_isAgreed) {
      ScaffoldMessenger.of(context).showSnackBar(
        const SnackBar(
          content: Text('请同意用户协议和隐私政策'),
          backgroundColor: Colors.red,
        ),
      );
    }
  }

  @override
  void dispose() {
    _nameController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('完善个人信息'),
      ),
      body: SafeArea(
        child: SingleChildScrollView(
          child: Padding(
            padding: const EdgeInsets.all(24.0),
            child: Form(
              key: _formKey,
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Center(
                    child: Text(
                      '请填写真实信息，以获取准确的命理分析',
                      style: TextStyle(
                        color: AppTheme.subtitleColor,
                        fontSize: 14,
                      ),
                    ),
                  ),
                  const SizedBox(height: 24),
                  // 姓名
                  _buildFormLabel('姓名'),
                  const SizedBox(height: 8),
                  TextFormField(
                    controller: _nameController,
                    decoration: const InputDecoration(
                      hintText: '请输入您的真实姓名',
                    ),
                    validator: (value) {
                      if (value == null || value.isEmpty) {
                        return '请输入姓名';
                      }
                      return null;
                    },
                  ),
                  const SizedBox(height: 16),
                  // 性别
                  _buildFormLabel('性别'),
                  const SizedBox(height: 8),
                  Row(
                    children: [
                      _buildRadioOption('男', _gender == '男', (value) {
                        setState(() {
                          _gender = '男';
                        });
                      }),
                      const SizedBox(width: 24),
                      _buildRadioOption('女', _gender == '女', (value) {
                        setState(() {
                          _gender = '女';
                        });
                      }),
                    ],
                  ),
                  const SizedBox(height: 16),
                  // 出生日期（农历）
                  _buildFormLabel('出生日期（农历）'),
                  const SizedBox(height: 8),
                  Row(
                    children: [
                      Expanded(
                        child: _buildDropdown(
                          _selectedYear,
                          _generateYears(),
                          (value) {
                            setState(() {
                              _selectedYear = value!;
                            });
                          },
                        ),
                      ),
                      const SizedBox(width: 8),
                      Expanded(
                        child: _buildDropdown(
                          _selectedMonth,
                          _generateMonths(),
                          (value) {
                            setState(() {
                              _selectedMonth = value!;
                            });
                          },
                        ),
                      ),
                      const SizedBox(width: 8),
                      Expanded(
                        child: _buildDropdown(
                          _selectedDay,
                          _generateDays(),
                          (value) {
                            setState(() {
                              _selectedDay = value!;
                            });
                          },
                        ),
                      ),
                    ],
                  ),
                  const SizedBox(height: 16),
                  // 出生时辰
                  _buildFormLabel('出生时辰'),
                  const SizedBox(height: 8),
                  _buildDropdown(
                    _selectedTime,
                    _generateTimeSlots(),
                    (value) {
                      setState(() {
                        _selectedTime = value!;
                      });
                    },
                  ),
                  const SizedBox(height: 16),
                  // 出生地
                  _buildFormLabel('出生地'),
                  const SizedBox(height: 8),
                  Row(
                    children: [
                      Expanded(
                        child: _buildDropdown(
                          _selectedProvince,
                          ['北京市', '上海市', '广东省', '江苏省'],
                          (value) {
                            setState(() {
                              _selectedProvince = value!;
                            });
                          },
                        ),
                      ),
                      const SizedBox(width: 8),
                      Expanded(
                        child: _buildDropdown(
                          _selectedCity,
                          ['北京市', '朝阳区', '海淀区'],
                          (value) {
                            setState(() {
                              _selectedCity = value!;
                            });
                          },
                        ),
                      ),
                    ],
                  ),
                  const SizedBox(height: 16),
                  // 职业
                  _buildFormLabel('职业'),
                  const SizedBox(height: 8),
                  _buildDropdown(
                    _selectedOccupation,
                    ['学生', '企业职员', '自由职业', '公务员', '教师', '医生', '工程师', '其他'],
                    (value) {
                      setState(() {
                        _selectedOccupation = value!;
                      });
                    },
                  ),
                  const SizedBox(height: 16),
                  // 婚姻状况
                  _buildFormLabel('婚姻状况'),
                  const SizedBox(height: 8),
                  _buildDropdown(
                    _selectedMaritalStatus,
                    ['未婚', '已婚', '离异', '丧偶'],
                    (value) {
                      setState(() {
                        _selectedMaritalStatus = value!;
                      });
                    },
                  ),
                  const SizedBox(height: 32),
                  // 生成命理基本盘按钮
                  CustomButton(
                    text: '生成我的命理基本盘',
                    onPressed: _generateChart,
                  ),
                  const SizedBox(height: 16),
                  // 用户协议
                  Center(
                    child: Text.rich(
                      TextSpan(
                        text: '点击上方按钮，即表示您同意我们的',
                        style: const TextStyle(
                          fontSize: 12,
                          color: AppTheme.lightTextColor,
                        ),
                        children: [
                          TextSpan(
                            text: '用户协议',
                            style: const TextStyle(
                              color: AppTheme.primaryColor,
                            ),
                            recognizer: TapGestureRecognizer()
                              ..onTap = () {
                                // 打开用户协议
                              },
                          ),
                          const TextSpan(text: '和'),
                          TextSpan(
                            text: '隐私政策',
                            style: const TextStyle(
                              color: AppTheme.primaryColor,
                            ),
                            recognizer: TapGestureRecognizer()
                              ..onTap = () {
                                // 打开隐私政策
                              },
                          ),
                        ],
                      ),
                      textAlign: TextAlign.center,
                    ),
                  ),
                ],
              ),
            ),
          ),
        ),
      ),
    );
  }

  Widget _buildFormLabel(String label) {
    return Text(
      label,
      style: const TextStyle(
        fontSize: 14,
        fontWeight: FontWeight.bold,
        color: AppTheme.textColor,
      ),
    );
  }

  Widget _buildRadioOption(String label, bool isSelected, Function(bool?) onChanged) {
    return Row(
      children: [
        Radio<bool>(
          value: true,
          groupValue: isSelected,
          activeColor: AppTheme.primaryColor,
          onChanged: (value) => onChanged(value),
        ),
        Text(
          label,
          style: const TextStyle(
            fontSize: 14,
            color: AppTheme.textColor,
          ),
        ),
      ],
    );
  }

  Widget _buildDropdown(String value, List<String> items, Function(String?) onChanged) {
    return Container(
      decoration: BoxDecoration(
        border: Border.all(color: AppTheme.dividerColor),
        borderRadius: BorderRadius.circular(8),
      ),
      child: DropdownButtonHideUnderline(
        child: DropdownButton<String>(
          value: value,
          isExpanded: true,
          padding: const EdgeInsets.symmetric(horizontal: 16),
          borderRadius: BorderRadius.circular(8),
          items: items.map((String item) {
            return DropdownMenuItem<String>(
              value: item,
              child: Text(
                item,
                style: const TextStyle(
                  fontSize: 14,
                  color: AppTheme.textColor,
                ),
              ),
            );
          }).toList(),
          onChanged: onChanged,
        ),
      ),
    );
  }
} 